package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//	创建一个map 集合
		Map<String, Object> map = new HashMap<>();
		//	在MongoDB中查询所有数据并按照更新时间进行降序排列
		Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "updateTime")).limit(1);
		//	获取数据
		UserListenProcess userListenProcess = this.mongoTemplate.findOne(query, UserListenProcess.class, this.getCollectionName(userId));
		//	判断是否能够获取数据
		if (null != userListenProcess){
			//	存储数据
			map.put("albumId",userListenProcess.getAlbumId());
			map.put("trackId",userListenProcess.getTrackId());
		}
		//	返回数据
		return map;
	}

	@Override
	public void updateListenProcess(UserListenProcess userListenProcess, Long userId) {
		//	构建查询条件
		Query query = Query.query(Criteria.where("trackId").is(userListenProcess.getTrackId()).and("userId").is(userId));
		//	获取集合名称
		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, this.getCollectionName(userId));
		if (null == listenProcess){
			//	创建一个新对象
			listenProcess = new UserListenProcess();
			//	属性拷贝；
			BeanUtils.copyProperties(userListenProcess, listenProcess);
			//	数据赋值
			listenProcess.setUserId(userId);
			listenProcess.setCreateTime(new Date());
			listenProcess.setUpdateTime(new Date());
		} else {
			//	更新
			listenProcess.setBreakSecond(userListenProcess.getBreakSecond());
			listenProcess.setUpdateTime(new Date());
		}
		//	新增或修改;
		mongoTemplate.save(listenProcess,this.getCollectionName(userId));
		//	防止用户恶意刷播放量. set key value ex 24 nx; == 分布式锁思想！
		String key = userListenProcess.getUserId() + "_" + userListenProcess.getTrackId();
		Boolean result = redisTemplate.opsForValue().setIfAbsent(key, "1", 24, TimeUnit.HOURS);
		//	判断
		if (result){
			//	获取当前播放量 track_stat + 1; album_stat + 1;
			//	异步: TrackStatMqVo
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			//	业务编号，去重.
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));
			trackStatMqVo.setCount(1);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setTrackId(userListenProcess.getTrackId());

			//	发送消息;
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
		return;
	}

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//	数据库，集合，文档-内容
		//	db.userListenProcess_userId.find({"trackId":trackId,"userId":userId})
		Query query = Query.query(Criteria.where("trackId").is(trackId).and("userId").is(userId));
		//	获取集合名称
		String collectionName = getCollectionName(userId);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//	判断这个对象是否为空
		if (null != userListenProcess){
			return userListenProcess.getBreakSecond();
		}
		//	默认返回数据
		return new BigDecimal("0");
	}

	@NotNull
	private static String getCollectionName(Long userId) {
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		return collectionName;
	}
}
